<template>
  <div class="image-uploader">
    <a-upload-dragger
      :file-list="fileList"
      :before-upload="handleBeforeUpload"
      :show-upload-list="false"
      accept="image/*"
      @change="handleFileChange"
      class="upload-dragger"
    >
      <div class="upload-content">
        <p class="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p class="ant-upload-text">点击或拖拽图片到此区域上传</p>
        <p class="ant-upload-hint">
          支持 JPG、PNG、GIF、BMP 格式，文件大小不超过 10MB
        </p>
      </div>
    </a-upload-dragger>
    
    <!-- 图片预览 -->
    <div v-if="previewImage" class="image-preview">
      <div class="preview-container">
        <img :src="previewImage" alt="预览图片" class="preview-img" />
        <div class="preview-actions">
          <a-button @click="decodeImage" type="primary" :loading="isDecoding">
            <template #icon>
              <ScanOutlined />
            </template>
            {{ isDecoding ? '解码中...' : '开始解码' }}
          </a-button>
          <a-button @click="clearPreview" type="text" class="clear-btn">
            <template #icon>
              <DeleteOutlined />
            </template>
            清除
          </a-button>
        </div>
      </div>
    </div>
    
    <!-- 解码进度 -->
    <div v-if="isDecoding" class="decoding-progress">
      <a-spin size="large" />
      <p>正在解码二维码...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadFile } from 'ant-design-vue'
import {
  InboxOutlined,
  ScanOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { decodeFromFile, DecodeResult } from '../utils/qrDecoder'

// 定义事件
const emit = defineEmits<{
  'decode-success': [result: DecodeResult]
  'decode-error': [error: string]
}>()

// 响应式数据
const fileList = ref<UploadFile[]>([])
const previewImage = ref('')
const currentFile = ref<File | null>(null)
const isDecoding = ref(false)

// 文件上传前的验证
const handleBeforeUpload = (file: File) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }
  
  // 检查文件大小（10MB）
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB！')
    return false
  }
  
  return false // 阻止自动上传
}

// 处理文件变化
const handleFileChange = (info: any) => {
  
  const { file } = info
  
  if (file.status === 'removed') {
    clearPreview()
    return
  }
  
  // 由于使用了 :before-upload="handleBeforeUpload" 并返回 false，
  // 文件不会有 status，我们直接处理原始文件
  const targetFile = file.originFileObj || file
  
  if (targetFile) {
    currentFile.value = targetFile
    
    const reader = new FileReader()
    reader.onload = (e) => {
      previewImage.value = e.target?.result as string
      
      // 自动触发解码
      nextTick(() => {
        decodeImage()
      })
    }
    
    reader.onerror = (error) => {
      message.error('图片读取失败')
    }

    reader.readAsDataURL(targetFile)
  } else {
    console.error('没有找到可用的文件对象:', file)
    message.error('文件处理失败，请重新选择')
  }
}

// 解码图片
const decodeImage = async () => {
  if (!currentFile.value) {
    console.error('没有文件可解码')
    message.error('请先选择图片文件')
    return
  }

  isDecoding.value = true
  
  try {
    const result = await decodeFromFile(currentFile.value)
    emit('decode-success', result)
    message.success('二维码解码成功！')
  } catch (error) {
    console.error('=== 解码失败 ===', error)
    console.error('错误详情:', {
      message: error instanceof Error ? error.message : '未知错误',
      stack: error instanceof Error ? error.stack : undefined
    })
    const errorMessage = error instanceof Error ? error.message : '解码失败'
    emit('decode-error', errorMessage)
    message.error(errorMessage)
  } finally {
    isDecoding.value = false
  }
}

// 清除预览
const clearPreview = () => {
  previewImage.value = ''
  currentFile.value = null
  fileList.value = []
}
</script>

<style scoped>
.image-uploader {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-dragger {
  flex: 1;
  min-height: 200px;
}

.upload-content {
  padding: 40px 20px;
}

.ant-upload-drag-icon {
  font-size: 48px;
  color: #667eea;
  margin-bottom: 16px;
}

.ant-upload-text {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.ant-upload-hint {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0;
}

.image-preview {
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  background: #fafafa;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  gap: 16px;
}

.preview-img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.clear-btn {
  color: #ff4d4f;
}

.clear-btn:hover {
  color: #ff7875;
  background-color: #fff2f0;
}

.decoding-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px 20px;
  text-align: center;
  background: #f9f9f9;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.decoding-progress p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-content {
    padding: 20px 10px;
  }
  
  .ant-upload-drag-icon {
    font-size: 36px;
  }
  
  .ant-upload-text {
    font-size: 14px;
  }
  
  .ant-upload-hint {
    font-size: 12px;
  }
  
  .preview-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .preview-actions .ant-btn {
    width: 100%;
  }
}
</style>